package com.dhkj.circle.ui.activity;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;

import com.dhkj.circle.R;
import com.dhkj.circle.constant.SQLConst;
import com.dhkj.circle.constant.SystemConst;
import com.dhkj.circle.db.sqlite.InfoDBSQLite;
import com.dhkj.circle.thread.ThreadPoolManager;
import com.dhkj.circle.utils.DBHelper;
import com.dhkj.circle.utils.QMUIView;
import com.dhkj.circle.utils.SystemUIUtils;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SystemManagerActivity extends Activity {
    @BindView(R.id.sys_manager_topbar)
    QMUITopBar sys_manager_topbar;

    @BindView(R.id.group_list_item_contact)
    QMUIGroupListView mGroupListContact;
    private int mCurrentDialogStyle = R.style.QMUI_Dialog;
    private List<String> dataname = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_manager);
        ButterKnife.bind(this);
        QMUIDisplayHelper.setFullScreen(this);

//        sys_manager_topbar.addLeftBackImageButton().setOnClickListener(v -> finish()); .33w
        sys_manager_topbar.setTitle("系统设置");
        print();
    }

    private void print() {
        QMUICommonListItemView listItemName = mGroupListContact.createItemView("机器号");
        listItemName.setDetailText(SystemConst.getDriver_id());
        listItemName.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        listItemName.setTag(1);

        QMUICommonListItemView setPass = mGroupListContact.createItemView("设置密码");
        setPass.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        setPass.setTag(2);

        QMUICommonListItemView getVersion = mGroupListContact.createItemView("版本号");
        getVersion.setDetailText(SystemConst.version);
        getVersion.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);


        mGroupListContact.removeAllViews();
        QMUIGroupListView.newSection(this)
                .setTitle("系统设置")
                .addItemView(listItemName, driveOnClick)
                .addItemView(setPass, driveOnClick)
                .addItemView(getVersion, null)
                .addTo(mGroupListContact);
        QMUICommonListItemView ipAddr = mGroupListContact.createItemView("数据库IP地址");
        ipAddr.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        ipAddr.setTag(1);
        ipAddr.setDetailText(SQLConst.getInstance().getSqlIpAddr());

        QMUICommonListItemView ipPort = mGroupListContact.createItemView("数据库IP端口");
        ipPort.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        ipPort.setDetailText(SQLConst.getInstance().getSqlPort());
        ipPort.setTag(2);

        QMUICommonListItemView sqlName = mGroupListContact.createItemView("数据库用户名");
        sqlName.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        sqlName.setDetailText(SQLConst.getInstance().getSqlName());
        sqlName.setTag(3);

        QMUICommonListItemView sqlPass = mGroupListContact.createItemView("数据库密码");
        sqlPass.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        sqlPass.setTag(4);

        QMUICommonListItemView sqlData = mGroupListContact.createItemView("数据库名");
        sqlData.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON);
        sqlData.setDetailText(SQLConst.getInstance().getSqlDBName());
        sqlData.setTag(5);


        QMUIGroupListView.newSection(this)
                .setTitle("数据库直联设置")
                .addItemView(ipAddr, OnClick)
                .addItemView(ipPort, OnClick)
                .addItemView(sqlName, OnClick)
                .addItemView(sqlPass, OnClick)
                .addTo(mGroupListContact);

        QMUIGroupListView.newSection(this)
                .addItemView(sqlData, OnClick)
                .addTo(mGroupListContact);
    }

    View.OnClickListener driveOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch ((int) v.getTag()) {
                case 1:
                    showDeriverIdDialog();
                    break;
                case 2:
                    showDwmmDialog();
                    break;
            }
        }
    };

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        SystemUIUtils.setStickFullScreen(getWindow().getDecorView());
    }

    View.OnClickListener OnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch ((int) v.getTag()) {
                case 1:
                    showIpAddDialog();
                    break;
                case 2:
                    showIpPortDialog();
                    break;
                case 3:
                    showSqlNameDialog();
                    break;
                case 4:
                    showSqlPassDialog();
                    break;
                case 5:
                    setData();
                    break;
                case 6:

                    break;

            }
        }
    };

    private void setData() {
        ThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                DBHelper dbHelper = new DBHelper();
                Connection connection = dbHelper.getConectior2();
                PreparedStatement semt = null;
                ResultSet rs = null;
                List<String> list = new ArrayList<>();
                try {
                    semt = connection.prepareStatement("SELECT Name FROM Master..SysDatabases ORDER BY Name");
                    rs = semt.executeQuery();
                    while (rs.next()) {
                        list.add(rs.getString("Name"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    dbHelper.close(connection, semt, rs);
                }
                dataname = list;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showDataName();
                    }
                });
            }
        });

    }

    private void showIpAddDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("设置数据库IP地址")
//                .setDefaultText(SysConst.getSysSQLBate().getSqlIpAddr())
                .setPlaceholder(SQLConst.getInstance().getSqlIpAddr().equals("") ? "在此输入数据库IP地址" : SQLConst.getInstance().getSqlIpAddr())
                .setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED)
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    CharSequence text = builder.getEditText().getText();
                    if (text != null && !text.toString().equals("")) {
                        SQLConst.getInstance().setSqlIpAddr(text.toString());
                        print();
                        dialog.dismiss();
                    } else {
                        QMUIView.showError(this, "请输入数据库IP地址");
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void showIpPortDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("设置数据库IP端口")
//                .setDefaultText(SysConst.getSysSQLBate().getSqlPort())
                .setPlaceholder("在此输入数据库IP端口")
                .setInputType(InputType.TYPE_CLASS_NUMBER)
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    CharSequence text = builder.getEditText().getText();
                    if (text != null && !text.toString().equals("")) {
                        SQLConst.getInstance().setSqlPort(text.toString());
                        print();
                        dialog.dismiss();
                    } else {
                        QMUIView.showError(this, "请输入数据库IP端口");
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void showSqlNameDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("设置数据库用户名")
//                .setDefaultText(SysConst.getSysSQLBate().getSqlName())
                .setPlaceholder("在此输入数据库用户名")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    CharSequence text = builder.getEditText().getText();
                    if (text != null && !text.toString().equals("")) {
                        SQLConst.getInstance().setSqlName(text.toString());
                        print();
                        dialog.dismiss();
                    } else {
                        QMUIView.showError(this, "请输入数据库用户名");

                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void showDeriverIdDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("设置机号")
//                .setDefaultText(SysConst.getSysSQLBate().getSqlName())
//                .setPlaceholder("在此输入数据库用户名")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    CharSequence text = builder.getEditText().getText();
                    if (text != null && !text.toString().equals("")) {
                        SystemConst.setDriver_id(text.toString());
                        print();
                        dialog.dismiss();
                    } else {
                        QMUIView.showError(this, "请输入机号");

                    }
                })
                .create(mCurrentDialogStyle).show();
    }
    private void showDwmmDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("设置单位密码")
//                .setDefaultText(SysConst.getSysSQLBate().getSqlName())
//                .setPlaceholder("在此输入数据库用户名")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    CharSequence text = builder.getEditText().getText();
                    if (text != null && !text.toString().equals("")) {
                        SystemConst.setDwmm(text.toString());
                        print();
                        dialog.dismiss();
                    } else {
                        QMUIView.showError(this, "请输入单位密码");

                    }
                })
                .create(mCurrentDialogStyle).show();
    }
    private void showSqlPassDialog() {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(this);
        builder.setTitle("设置数据库密码")
                .setPlaceholder("在此输入数据库密码")
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", (dialog, index) -> dialog.dismiss())
                .addAction("确定", (dialog, index) -> {
                    CharSequence text = builder.getEditText().getText();
                    if (text != null && !text.toString().equals("")) {
                        SQLConst.getInstance().setSqlPass(text.toString());
                        print();
                        dialog.dismiss();
                    } else {
                        QMUIView.showError(this, "请输入数据库密码");

                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void showDataName() {
        if (dataname.size() > 0) {
            String[] items = dataname.toArray(new String[dataname.size()]);
            new QMUIDialog.MenuDialogBuilder(this)
                    .addItems(items, (dialog, which) -> {
                        SQLConst.getInstance().setSqlDBName(items[which]);
                        print();
                        dialog.dismiss();
                    })
                    .create(mCurrentDialogStyle).show();
        } else {
            QMUIView.showError(this, "数据库连接失败，请检查输入是否正确");
        }
    }

    @butterknife.OnClick({R.id.btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                InfoDBSQLite.getInfoDBSQLite().saveInfo();
                finish();
                break;
        }
    }
}
